<script setup>
import {useRoute} from "vue-router";
import {stateOptions} from "@/mixins/index.js";
import {useUserStore} from "@/store/index.js";
import {apiParam, fieldVisible} from "@/utils/index.js";
import {induce} from "@/utils/derive.js";
import {uuid} from "@/utils/random.js";
import {changeDateFormat, getNowDate} from "@/utils/time.js";
import {skyNoticeSuccess, skyNoticeError, skyMsgError, skyMsgWarning, skyMsgBox, skyMsgInfo, skyMsgSuccess} from "@/utils/sky.js";
import {getNewInfo} from "@/components/SkyWindow/index.js";
import {varietyApi} from "@/apis/CMS/frmVariety/index.js";
import {More} from "@element-plus/icons-vue";

const route = useRoute();
const userStore = useUserStore();
const skyDialogRef = ref();
const skyWindowRef = ref();
const formRef = ref();
const pageData = ref({
  showSearch: true,
  searchParams: {
    keyWord: "",
    sort: "asc",
    manage: true,
  },
  varietyParam: {
    VarietyCode: "",
    VarietyName: "",
  },
  pageParams: {
    pageNo: 1,
    SortFields: "FVarietyCode",
    direction: "asc",
    pageSize: 10,
  },
  ids: [],
  single: true,
  multiple: true,
  title: "工艺路线维护",
  confirmLoading: false,
  form: {
    VarietyCode: "",
    VarietyName: "",
    BillDate: getNowDate(),
    Remark: "",
    Items: [],
  },
  rules: {
    VarietyCode: [{required: true, message: "请输入品号编码", trigger: "blur"}],
    VarietyName: [{required: true, message: "请输入品号名称", trigger: "blur"}],
  },
  loading: false,
  total: 0,
  column: [],
  showTable: [
    {title: "品种编号", IsVisible: 1},
    {title: "品种名称", IsVisible: 1},
    {title: "排序", IsVisible: 1},
    {title: "日期", IsVisible: 1},
    {title: "状态", IsVisible: 1},
    {title: "备注", IsVisible: 1},
  ],
  tableList: [],
  windowTitle: "",
  windowObj: {},
  windowParam: {},
  windowCond: {},
});
const method = reactive({
  /** 关键字 */
  handleListKey: async () => {
    const data = apiParam("2.0", "CMS.VarietyDAL.Querybykeyvalue",
      [pageData.value.searchParams.keyWord, pageData.value.pageParams]);
    try {
      pageData.value.loading = true;
      pageData.value.tableList = [];
      const res = await varietyApi(data);
      pageData.value.searchParams.keyWord = "";
      pageData.value.total = res.data.recordsTotal;
      pageData.value.tableList = res.data.data;
      pageData.value.loading = false;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 搜索 */
  handleSearch: () => {
    pageData.value.pageParams.pageNo = 1;
    method.handleListKey();
  },
  /** 重置 */
  resetSearch: () => {
    method.resetSearchParams();
    method.handleListPage();
  },
  /** 重置搜索参数 */
  resetSearchParams: () => {
    pageData.value.searchParams = {
      keyWord: "",
      sort: "asc",
      manage: true,
    };
    pageData.value.varietyParam = {
      VarietyCode: "",
      VarietyName: "",
    };
    pageData.value.pageParams = {
      pageNo: 1,
      sortBy: "FVarietyCode",
      direction: "asc",
      pageSize: 10,
    };
  },
  /** 添加 */
  handleAdd: () => {
    // 打开弹出框
    skyDialogRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    // 标题
    pageData.value.title = "添加";
    pageData.value.form.BillDate = getNowDate();
  },
  /** 新增行 */
  handleAddItems: () => {
    pageData.value.form.Items.push({
      RecordId: uuid(),
      Sort: pageData.value.form.Items.length > 0 ?
        pageData.value.form.Items[pageData.value.form.Items.length - 1].Sort + 1 : 1,
      ProcedureCode: "",
      ProcedureName: "",
      WaitTime: 0,
      MadeTime: 0,
      DefProcUnitCode: "",
      DefProcUnitName: "",
      Remark: "",
    });
  },
  /** 删除行 */
  handleDeleteItems: (row) => {
    const id = row.RecordId;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除参数名称[" + row.ProcedureName + "]么？")
      .then(() => {
        try {
          const index = pageData.value.form.Items.find(item => item.RecordId === id);
          pageData.value.form.Items.splice(index, 1);
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 删除 */
  handleDelete: (row) => {
    const id = row.RecordId;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除参数名称[" + row.VarietyName + "]么？")
      .then(async () => {
        try {
          const data = apiParam("2.0", "CMS.VarietyDAL.Delete", [id]);
          await varietyApi(data);
          await method.handleListPage();
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          await method.handleListPage();
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 批量删除 */
  handleBatchDelete: () => {
    return skyMsgInfo("暂不支持批量删除");
  },
  /** 修改 */
  handleUpdate: (row) => {
    // 打开弹出框
    skyDialogRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    pageData.value.title = "修改";
    const id = row ? row.RecordId : pageData.value.ids[0];
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEcho(id);
  },
  /** 回显数据 */
  handleEcho: async (id) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const data = apiParam("2.0", "CMS.VarietyDAL.GetById", [id]);
      const res = await varietyApi(data);
      pageData.value.form = res.data;
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    pageData.value.confirmLoading = true;
    (formRef.value).validate(async (valid) => {
      if (valid) {
        if (pageData.value.form.RecordId) {
          try {
            const data = apiParam("2.0", "CMS.VarietyDAL.Update",
              [pageData.value.form]);
            await varietyApi(data);
            skyNoticeSuccess("修改成功🌻");
            pageData.value.confirmLoading = false;
            skyDialogRef.value.skyQuickClose();
            method.resetForm();
            await method.handleListPage();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("修改失败，请刷新重试🌻");
          }
        } else {
          try {
            const data = apiParam("2.0", "CMS.VarietyDAL.Create",
              [pageData.value.form]);
            await varietyApi(data);
            skyNoticeSuccess("添加成功🌻");
            pageData.value.confirmLoading = false;
            skyDialogRef.value.skyQuickClose();
            method.resetForm();
            await method.handleListPage();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    skyDialogRef.value.skyClose();
  },
  /** 清空表单数据 */
  resetForm: () => {
    nextTick(() => {
      if (formRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
      }
    });
    pageData.value.form = {
      VarietyCode: "",
      VarietyName: "",
      BillDate: getNowDate(),
      Remark: "",
      Items: [],
    };
  },
  /** 导出 */
  handleDerive: () => {
    const column = [
      {title: "录入人", dataIndex: "Creator"},
      {title: "录入时间", dataIndex: "CreateTime"},
      {title: "修改人", dataIndex: "LastModifier"},
      {title: "修改时间", dataIndex: "LastModifyTime"},
    ];
    induce("工艺路线维护报表", [...pageData.value.column, ...column], pageData.value.tableList);
    skyMsgSuccess("导出成功");
    method.handleListPage();
  },
  /** 是否多选 */
  handleSelectionChange: (selection) => {
    pageData.value.ids = selection.map((item) => item.RecordId);
    pageData.value.single = selection.length !== 1; // 单选
    pageData.value.multiple = !selection.length; // 多选
  },
  /** 表格表头 */
  handleListMeter: async () => {
    const data = apiParam("2.0", "SYS.UserColumnDefineDAL.Query",
      [{UserCode: userStore.userid, Context: route.path}]);
    try {
      const res = await varietyApi(data);
      pageData.value.column = res.data.Columns.map(item => {
        return {
          title: item.DisplayCaption,
          dataIndex: item.DisplayFieldName,
        }
      });
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 数据表格 */
  handleListPage: async () => {
    const data = apiParam("2.0", "CMS.VarietyDAL.Querybypage",
      [pageData.value.varietyParam, pageData.value.pageParams]);
    try {
      pageData.value.loading = true;
      pageData.value.tableList = [];
      const res = await varietyApi(data);
      pageData.value.total = res.data.recordsTotal;
      pageData.value.tableList = res.data.data;
      pageData.value.loading = false;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 打开来源参数 */
  handleOpenWindow: (title, data) => {
    // 打开弹出框
    skyWindowRef.value.skyOpen();
    // 判断参数
    if (title === "工序编号") {
      pageData.value.windowParam.Code = "Procedure";
      pageData.value.windowParam.Seq = "0001";
    }
    // 标题
    pageData.value.windowTitle = title;
    pageData.value.windowObj = data;
    // 获取来源条件
    getNewInfo(pageData.value.windowParam).then(res => {
      pageData.value.windowCond = res;
      method.dealWindowData(title, res);
    });
  },
  /** 处理条件 */
  dealWindowData: (title, value) => {
    if (title === "工序编号") {
      value.Conditions[0].ConValue = "";
    }
  },
  /** 选择指定来源参数 */
  handleWindowConfirm: (val) => {
    if (pageData.value.windowTitle === "工序编号") {
      const index = pageData.value.form.Items.findIndex(item => item.RecordId === pageData.value.windowObj.RecordId);
      pageData.value.form.Items[index].ProcedureCode = val?.FlowCode;
      pageData.value.form.Items[index].ProcedureName = val?.FlowName;
    }
    pageData.value.windowTitle = "";
    pageData.value.windowObj = {};
    pageData.value.windowParam = {};
    pageData.value.windowCond = {};
    skyWindowRef.value.skyQuickClose();
  },
  /** 取消来源参数 */
  handleWindowCancel: () => {
    skyWindowRef.value.skyClose();
  },
});
onMounted(() => {
  method.handleListMeter();
  method.handleListPage();
});
</script>

<!-- 工艺路线维护 -->
<template>
  <div class="sky-flex">
    <SkyCard>
      <!-- 搜索条件 -->
      <el-form v-show="pageData.showSearch" :inline="true">
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            style="width: 240px"
            placeholder="请输入关键字"
            v-model="pageData.searchParams.keyWord"
            clearable
            @keyup.enter.native="method.handleListKey"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-select v-model="pageData.searchParams.sort" style="width: 240px" clearable
                     @keyup.enter.native="method.handleListPage">
            <el-option label="升序" value="asc"/>
            <el-option label="降序" value="desc"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示管理字段" prop="manage">
          <el-checkbox v-model="pageData.searchParams.manage"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="method.handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="method.resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="plus" plain @click="method.handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="delete" plain @click="method.handleBatchDelete()" :disabled="pageData.multiple">
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="edit" plain @click="method.handleUpdate()" :disabled="pageData.single">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="download" plain @click="method.handleDerive">导出</el-button>
        </el-col>
        <SkyToolbar v-model:showSearch="pageData.showSearch" v-model:showColumns="pageData.showTable"
                    @refreshTable="method.handleListPage"></SkyToolbar>
      </el-row>
      <br/>
      <!-- 数据表格 -->
      <el-table
        v-loading="pageData.loading"
        border
        :data="pageData.tableList"
        empty-text="暂时没有数据哟🌻"
        @selection-change="method.handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column v-if="fieldVisible('品种编号', pageData.showTable)" label="品种编号" prop="VarietyCode" width="120"
                         align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column v-if="fieldVisible('品种名称', pageData.showTable)" label="品种名称" prop="VarietyName" width="150"
                         align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column v-if="fieldVisible('日期', pageData.showTable)" label="日期" prop="BillDate" width="150" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            {{ changeDateFormat(scope.row.BillDate, "YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column v-if="fieldVisible('状态', pageData.showTable)" label="状态" prop="State" width="120" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            <SkyTag :tagOptions="stateOptions" :value="scope.row.State"></SkyTag>
          </template>
        </el-table-column>
        <el-table-column v-if="fieldVisible('备注', pageData.showTable)" label="备注" prop="Remark" width="180" align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column v-if="pageData.searchParams.manage" label="录入人" prop="Creator" width="130"
                         align="center"></el-table-column>
        <el-table-column v-if="pageData.searchParams.manage" label="录入时间" prop="CreateTime" width="200" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            {{ changeDateFormat(scope.row.CreateTime, "YYYY-MM-DD hh:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column v-if="pageData.searchParams.manage" label="修改人" prop="LastModifier" width="130"
                         align="center"></el-table-column>
        <el-table-column v-if="pageData.searchParams.manage" label="修改时间" prop="LastModifyTime" width="200" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            {{ changeDateFormat(scope.row.LastModifyTime, "YYYY-MM-DD hh:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改🌻" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="method.handleUpdate(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除🌻" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="method.handleDelete(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pageData.pageParams.pageNo"
        v-model:page-size="pageData.pageParams.pageSize"
        v-show="pageData.total > 0"
        background
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
        @size-change="method.handleListPage"
        @current-change="method.handleListPage"
      />
      <!-- 添加 OR 修改 -->
      <SkyDialog
        ref="skyDialogRef"
        :title="pageData.title"
        @skyConfirm="method.handleConfirm"
        @skyCancel="method.handleCancel"
        :loading="pageData.confirmLoading"
        :width="800"
        :height="500"
      >
        <template #content>
          <div class="sky-flex">
            <SkyCard>
              <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="auto" status-icon>
                <el-row>
                  <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                    <el-form-item label="工段编码" prop="VarietyCode">
                      <el-input v-model="pageData.form.VarietyCode" placeholder="请输入品号编号" clearable/>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                    <el-form-item label="日期" prop="BillDate" class="p-l-10px">
                      <el-date-picker style="width: 100%;" v-model="pageData.form.BillDate" type="date" placeholder="请选择日期"
                                      clearable/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                    <el-form-item label="工段编码" prop="VarietyName">
                      <el-input v-model="pageData.form.VarietyName" placeholder="请输入品号名称" clearable/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                    <el-form-item label="备注" prop="Remark">
                      <el-input v-model="pageData.form.Remark" :rows="3" type="textarea" placeholder="请输入备注"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </SkyCard>
            <SkyCard>
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <el-button type="primary" icon="plus" plain @click="method.handleAddItems">新增行</el-button>
                </el-col>
              </el-row>
              <br/>
              <el-table
                :data="pageData.form.Items"
                empty-text="暂时没有数据哟🌻"
                border
              >
                <el-table-column label="序号" prop="Sort" width="150" align="center">
                  <template #default="scope">
                    <el-input-number style="width: 100%;" v-model="scope.row.Sort"/>
                  </template>
                </el-table-column>
                <el-table-column label="工序名称" prop="ProcedureName" width="200" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.ProcedureName" placeholder="请选择工序名称" clearable>
                      <template #append>
                        <el-button :icon="More" @click="method.handleOpenWindow('工序编号', scope.row)"/>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="工序编号" prop="ProcedureCode" width="200" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.ProcedureCode" placeholder="请输入工序编号" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="前置时间" prop="WaitTime" width="200" align="center">
                  <template #default="scope">
                    <el-input-number style="width: 100%;" v-model="scope.row.WaitTime"/>
                  </template>
                </el-table-column>
                <el-table-column label="加工时间" prop="MadeTime" width="200" align="center">
                  <template #default="scope">
                    <el-input-number style="width: 100%;" v-model="scope.row.MadeTime"/>
                  </template>
                </el-table-column>
                <el-table-column label="默认加工单元编号" prop="DefProcUnitCode" width="200" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.DefProcUnitCode" placeholder="请输入默认加工单元编号" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="默认加工单元名称" prop="DefProcUnitName" width="200" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.DefProcUnitName" placeholder="请输入默认加工单元名称" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="Remark" width="200" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.Remark" placeholder="请输入备注" clearable/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" prop="Operate" width="100" align="center">
                  <template #default="scope">
                    <el-tooltip content="删除🌻" placement="top">
                      <el-button
                        type="danger"
                        icon="Delete"
                        circle
                        plain
                        @click="method.handleDeleteItems(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </SkyCard>
          </div>
        </template>
      </SkyDialog>
      <!-- 来源参数 -->
      <SkyWindow
        ref="skyWindowRef"
        :title="pageData.windowTitle"
        :condition="pageData.windowCond"
        @skyConfirm="method.handleWindowConfirm"
        @skyCancel="method.handleWindowCancel"
      >
      </SkyWindow>
    </SkyCard>
  </div>
</template>

<style scoped lang="scss">

</style>
